package hotel.base.oversea.utils.redis;

/**
*@Description: Jedis 获取相关redis连接
*@Author: Zhang·jz
*@date: 2021/3/10
*/
import hotel.base.oversea.config.PropertyUtil;
import hotel.base.oversea.constant.CommonBaseConstants;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {
	// 服务器ip地址
	private static String ADDR = PropertyUtil.getProperty("common.redis.sec.host");

	// 端口
	private static String PORT = PropertyUtil.getProperty("common.redis.sec.port");

	// 密码
	private static String PASSWORD = PropertyUtil.getProperty("common.redis.sec.password");

	// 连接实例的最大连接数
	private static int MAX_ACTIVE = 1024;

	// 连接池中能存在状态为空闲的个数
	private static int MAX_IDLE = 200;

	// 等待超时时间,单位毫秒
	private static int MAX_WAIT = 2000;

	// 连接超时的时间
	private static int TIMEOUT = 3000;

	// 在borrow一个jedis实例时，是否提前进行validate操作，如果为true得到的实例均是可用的
	private static boolean TEST_ON_BORROW = true;

	// 连接池
	private static JedisPool jpool = null;

	/*
	 * 初始化连接池
	 */
	static {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxWaitMillis(MAX_WAIT);
			config.setMaxIdle(MAX_IDLE);
			config.setMaxTotal(MAX_ACTIVE);
			config.setTestOnBorrow(TEST_ON_BORROW);
			jpool = new JedisPool(config, ADDR, Integer.valueOf(PORT), TIMEOUT,PASSWORD, CommonBaseConstants.REDIS_DB_5);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 获取Jedis实例
	 */
	public static Jedis getJedis() {
		if (jpool != null) {
			return jpool.getResource();
		} else {
			return null;
		}
	}

	/*
	 * 回收Jedis
	 */
	public static void returnJedis(final Jedis jedis) {
		if (jedis != null) {
			jpool.returnResource(jedis);
		}
	}

	public static String get(String key) {
		String value = null;
		Jedis jedis = null;
		try {
			jedis = getJedis();
			value = jedis.get(key);
		} catch (Exception e) {
			if (jedis != null) {
				jedis.close();
			}
			e.printStackTrace();
		} finally {
			returnJedis(jedis);
		}
		return value;
	}

	public static String set(String key, String value) {
		Jedis jedis = null;
		String ans = null;
		try {
			jedis = getJedis();
			ans = jedis.set(key, value);
		} catch (Exception e) {
			//释放redis对象
			if (jedis != null) {
				jedis.close();
			}
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnJedis(jedis);
		}
		return ans;
	}

	public static String setex(String key, String value, int seconds) {
		Jedis jedis = null;
		String ans = null;
		try {
			jedis = getJedis();
			ans = jedis.setex(key, seconds, value);
		} catch (Exception e) {
			if (jedis != null) {
				jedis.close();
			}
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnJedis(jedis);
		}
		return ans;
	}

}
///*
//*测试
//*/
//import redis.clients.jedis.Jedis;
//
//public class Operation {
//	public static void main(String[] args) {
//		Jedis jedis = Connections.getJedis();
//		jedis.set("java", "测试");
//		System.out.println(jedis.get("java"));
//		Connections.returnJedis(jedis);
//	}
//}
